package sel.me.websocket.learning.auth;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import sel.me.websocket.learning.domain.AdminUserDO;

/**
 * 授权
 * @author vis
 *    
 */
public class MyAuthorizingRealm extends AuthorizingRealm {

	
	/**
	 * 为当前登陆成功的用户授予权限和角色，已经登陆成功了 
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		 
		// 获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
		VeeefunToken currentUsername = (VeeefunToken) super.getAvailablePrincipal(principals);
		SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
		// 实际中可能会像上面注释的那样从数据库取得
		if (null != currentUsername && currentUsername.getUsername().startsWith("admin")) {
			// 添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色
			simpleAuthorInfo.addRole("admin");
			// 添加权限
			simpleAuthorInfo.addStringPermission("admin:manage");
			//System.out.println("已为用户[admin]赋予了[admin]角色和[admin:manage]权限");
			return simpleAuthorInfo;
		}
		else if (null != currentUsername && "esl".equals(currentUsername.getUsername())) {
			// 添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色
			simpleAuthorInfo.addRole("admin");
			simpleAuthorInfo.addRole("esl");
			// 添加权限
			simpleAuthorInfo.addStringPermission("esl:manage");
			//System.out.println("已为用户[esl]赋予了[esl]角色和[esl:manage]权限");
			return simpleAuthorInfo;
		}
		else if (null != currentUsername && "shunwang".equals(currentUsername.getUsername())) {
			// 添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色
			simpleAuthorInfo.addRole("admin");
			simpleAuthorInfo.addRole("esl");
			// 添加权限
			simpleAuthorInfo.addStringPermission("esl:manage");
			//System.out.println("已为用户[esl]赋予了[esl]角色和[esl:manage]权限");
			return simpleAuthorInfo;
		}else if (null != currentUsername && "admin".equals(currentUsername)) {
			//System.out.println("当前用户[admin]无授权");
			return simpleAuthorInfo;
		}
		// 若该方法什么都不做直接返回null的话,就会导致任何用户访问/admin/listUser.jsp时都会自动跳转到unauthorizedUrl指定的地址
		// 详见applicationContext.xml中的<bean id="shiroFilter">的配置
		return null;
	}

	/**
	 * // 验证当前登录的用户，获取认证信息
	 * http://blog.csdn.net/xiangwanpeng/article/details/54802509
	 * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		//String principal = String.valueOf(authcToken.getPrincipal());            // 得到身份（用户名）
	   // String credentials = new String((char[])authcToken.getCredentials());    // 得到认证/凭证（密码）
	    //System.out.println(principal+"="+credentials);
		// 获取基于用户名和密码的令牌
		// 实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
		// 两个token的引用都是一样的,本例中是org.apache.shiro.authc.UsernamePasswordToken@33799a1e
	    VeeefunToken token = (VeeefunToken) authcToken;
		//System.out.println("验证当前Subject时获取到token为"+token);
		AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(token, token.getPassword()==null?"":token.getPassword(), this.getName());
		AdminUserDO adminUserDO = new AdminUserDO();
        adminUserDO.setUsername(token.getUsername());
        if(token.getUsername().startsWith("admin")) {
        	adminUserDO.setGroup("admin");
        }else {
            adminUserDO.setGroup("staff");
        }
		Session session = SecurityUtils.getSubject().getSession();
        session.setAttribute("currentUser",adminUserDO);
		return authcInfo;
		/*
		// User user = userService.getByUsername(token.getUsername());
		// if(null != user){
		// AuthenticationInfo authcInfo = new
		// SimpleAuthenticationInfo(user.getUsername(), user.getPassword(),
		// user.getNickname());
		// this.setSession("currentUser", user);
		// return authcInfo;
		// }else{
		// return null;
		// }
		// 此处无需比对,比对的逻辑Shiro会做,我们只需返回一个和令牌相关的正确的验证信息
		// 说白了就是第一个参数填登录用户名,第二个参数填合法的登录密码(可以是从数据库中取到的,本例中为了演示就硬编码了)
		// 这样一来,在随后的登录页面上就只有这里指定的用户和密码才能通过验证
		if ("admin".equals(token.getUsername())) {
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(
					"jadyer", "jadyer", this.getName());
			this.setSession("currentUser", "jadyer");
			return authcInfo;
			return new SimpleAuthenticationInfo(String.valueOf(principal), String.valueOf(credentials), this.getName());
		} else if ("test".equals(token.getUsername())) {
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo("admin",
					"admin", this.getName());
			return authcInfo;
		}
		// 没有返回登录用户名对应的SimpleAuthenticationInfo对象时,就会在LoginController中抛出UnknownAccountException异常
		return null;
		*/
	}


}
